//
//  InformationTopView.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/6.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "InformationTopView.h"
#import "LotteryNumCell.h"
#import "OpenLotteryRecordVC.h"
@interface InformationTopView()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) Home_LotteryModel *recordModel;
@property (nonatomic ,strong) UICollectionView *bottomCollectionView;

@end

@implementation InformationTopView{
    UIImageView *icon;
    QXLable     *labTitle;
    QXLable     *labTime;
    QXLable     *nextOpenlabTime;
    NSMutableArray     *arrData;
    NSMutableArray     *arrAlias;
    dispatch_source_t _timer;
}

- (instancetype)init{
    if (self=[super init]) {
//        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openLotteryVC)];
//        [self addGestureRecognizer:tap];
    }
    return self;
}

- (void)openLotteryVC{
    OpenLotteryRecordVC *vc =[[OpenLotteryRecordVC alloc]init];
    vc.lType=self.lotteryModel.LType;
    vc.title=[NSString stringWithFormat:@"%@开奖记录",self.lotteryModel.LTypeName];
    vc.lotteryType=[[BaseVM manage] getType:[self.lotteryModel.LType integerValue]];
    [[TGTools viewController:self].navigationController pushViewController:vc animated:YES];
}

- (instancetype)initWithModel:(Home_LotteryModel *)model{
    if (self=[self init]) {
        WS(weakSelf);
        _lotteryModel=model;
        self.backgroundColor=[UIColor whiteColor];
        icon=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat_icon"]];
        [self addSubview:icon];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf).with.offset(10);
            make.top.equalTo(weakSelf).offset(10);
            make.size.mas_equalTo(CGSizeMake(real_size(45), real_size(45)));
        }];
        
        labTitle=[[QXLable alloc]initTitle];
        [self addSubview:labTitle];
        [labTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon.mas_right).with.offset(13);
            make.top.equalTo(icon).with.offset(3);
        }];
        
        labTime=[[QXLable alloc]init];
        labTime.textAlignment=NSTextAlignmentRight;
        [self addSubview:labTime];
        [labTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakSelf).with.offset(-13);
            make.centerY.equalTo(labTitle);
        }];
        arrData=[NSMutableArray arrayWithArray:model.numArr];
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(labTitle);
//            make.bottom.equalTo(icon);
            make.top.equalTo(labTitle.mas_bottom).offset(5);
            make.right.equalTo(weakSelf);
            make.height.mas_equalTo(@(real_size(27)));
        }];
        
        [self addSubview:self.bottomCollectionView];
        [self.bottomCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.collectionView);
            make.top.equalTo(self.collectionView.mas_bottom);
            make.right.equalTo(weakSelf);
            make.height.mas_equalTo(@(real_size(27)));
        }];

        
        UIView *lineView=[[UIView alloc]init];
        lineView.backgroundColor=DEFAULTBGCOLOR;
        [self addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.bottomCollectionView.mas_bottom).offset(5);
            make.left.right.equalTo(self);
            make.height.mas_equalTo(@.7);
        }];
        
        
        nextOpenlabTime=[[QXLable alloc]init];
        [self addSubview:nextOpenlabTime];
        [nextOpenlabTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon);
            make.right.equalTo(self);
            make.top.equalTo(lineView.mas_bottom).with.offset(5);
            make.height.mas_equalTo(25);
        }];
        
        nextOpenlabTime.userInteractionEnabled =YES;
        UITapGestureRecognizer *openTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nextOpenlabClick:)];
        [nextOpenlabTime addGestureRecognizer:openTap];
        
    }
    return self;
}

-(void)nextOpenlabClick:(UITapGestureRecognizer *)tap{
    PublicWebVC *vc=[[PublicWebVC alloc]init];
    vc.url=@"http://mobile.c8.cn/News/LotteryTime";
    vc.title=@"六合彩-开奖时间";
    [[TGTools viewController:self].navigationController pushViewController:vc animated:YES];
}


- (void)setLotteryModel:(Home_LotteryModel *)lotteryModel{
    _lotteryModel=lotteryModel;
    [icon sd_setImageWithURL:[NSURL URLWithString:lotteryModel.Logo]];
    NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"第%@期",lotteryModel.Issue]];
    [attStr addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(1, attStr.length-2)];
    labTitle.attributedText=attStr;
    labTime.text=[NSString stringWithFormat:@"下期开奖：%@",lotteryModel.OpenTime];
    
    
    
    NSMutableAttributedString *attStr2=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"下期开奖时间：%@",lotteryModel.OpenTimeDesc]];
    [attStr2 addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTGDARKRAYCOLOR range:NSMakeRange(0, 2)];
    [attStr2 addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(2, attStr2.length-lotteryModel.OpenTimeDesc.length-3)];
    [attStr2 addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTGDARKRAYCOLOR range:NSMakeRange(6, attStr2.length-6)];
    nextOpenlabTime.attributedText = attStr2;
    
    
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    [arr addObjectsFromArray:lotteryModel.numArr];
    if (arr.count==7) {
        [arr insertObject:@"+" atIndex:arr.count-1];
    }
    arrData=arr;
    NSMutableArray *arr1=[[NSMutableArray alloc]init];
    [arr1 addObjectsFromArray:lotteryModel.aliasNumArr];
    if (arr1.count==7) {
        [arr1 insertObject:@"+" atIndex:arr1.count-1];
    }
    arrAlias=arr1;
    [self.collectionView reloadData];
    [self.bottomCollectionView reloadData];
    [self startTimer];
}



///链接scoket
- (void)connectScoket{
    if (!([[BaseVM manage]getType:[_lotteryModel.LType integerValue]]==LotteryNumTypeLottery)) {
        return;
    }
    [[SocketRocketUtility instance] SRWebSocketClose];
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:SCOKET_ADDRESS];
    WS(weakSelf);
    [[SocketRocketUtility instance] setAcceptBlock:^(ScoketLotteryModel *model) {
        if ([NSThread isMainThread]) {
            [weakSelf accpetMessage:model];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf accpetMessage:model];
            });
        }
    }];
    
    [[SocketRocketUtility instance] setConnectChange:^(NSInteger socketReadyState) {
        if ([NSThread isMainThread]) {
            //            [weakSelf changConnectStuatus:socketReadyState];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [weakSelf changConnectStuatus:socketReadyState];
            });
        }
    }];
    
}

#pragma mark - 接收的数据
- (void)accpetMessage:(ScoketLotteryModel *)model{
    if (model.MsgType==1) {
        if (model.MsgTypeChild==11) {
            [self.lotteryModel.LotteryArr removeAllObjects];
            [self.collectionView reloadData];
        }else{
            [[SocketRocketUtility instance] SRWebSocketClose];
        }
    }else{
        if (model.IsPeriod) {
            NSMutableAttributedString *attStr=[[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"第%@期",model.Content]];
            [attStr addAttribute:NSForegroundColorAttributeName value:NAVCOLOR range:NSMakeRange(1, attStr.length-2)];
            labTitle.attributedText=attStr;
            [self.lotteryModel.LotteryArr removeAllObjects];
            [self.collectionView reloadData];
        }else{
            if (model.Content.length==1) {
                model.Content=[NSString stringWithFormat:@"0%@",model.Content];
            }
            if (self.lotteryModel.LotteryArr.count<model.BallNo) {
                if (self.lotteryModel.LotteryArr.count==6) {
                    [self.lotteryModel.LotteryArr addObject:@"+"];
                }
                [self.lotteryModel.LotteryArr addObject:model.Content];
            }else{
                [self.lotteryModel.LotteryArr insertObject:model.Content atIndex:model.BallNo-1];
            }
            [self.collectionView reloadData];
        }
    }
    
}


#pragma mark -- 启动定时器
- (void)startTimer{
    [self cancleTimer];
    WS(weakSelf);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (![weakSelf.lotteryModel.OpenTime isEqualToString:@"正在开奖"]) {
            
            if ([weakSelf.recordModel.Issue isEqualToString:weakSelf.lotteryModel.Issue] &&[weakSelf.recordModel.CurrentIssue isEqualToString:weakSelf.lotteryModel.CurrentIssue]) {
                [weakSelf cancleTimer];
                weakSelf.lotteryModel.OpenTime=@"正在开奖";
                
            }else{
                NSArray *timeArr=[self.lotteryModel.OpenTime componentsSeparatedByString:@":"];
                int hour=[timeArr[0] intValue];
                int minutes=[timeArr[1] intValue];
                int second=[timeArr[2] intValue];
                if (second>0) {
                    second-=1;
                    weakSelf.lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
                }else if (minutes>0){
                    minutes-=1;
                    second=59;
                    weakSelf.lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
                }else if (hour>0){
                    hour-=1;
                    minutes=59;
                    second=59;
                    weakSelf.lotteryModel.OpenTime=[NSString stringWithFormat:@"%@:%@:%@",[TGTools getTime:hour],[TGTools getTime:minutes],[TGTools getTime:second]];
                }else{
                    [self cancleTimer];
                    weakSelf.lotteryModel.OpenTime=@"正在开奖";
                }
            }
            
            
        }else{
            
            [self cancleTimer];
            
            weakSelf.recordModel = weakSelf.lotteryModel;
        }
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self.lotteryModel.OpenTime isEqualToString:@"正在开奖"]) {
                [self cancleTimer];
                [self connectScoket];
            }
            labTime.text=[NSString stringWithFormat:@"下期开奖：%@",self.lotteryModel.OpenTime];
            
            [self.collectionView reloadData];
        });
        
    });
    dispatch_resume(_timer);
}


- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}


#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (collectionView==self.bottomCollectionView) {
        return arrAlias.count;
    }else{
        
        if ([_lotteryModel.LType integerValue]==65) {
            return _lotteryModel.PCArr.count;
        }else if ([[BaseVM manage]getType:[_lotteryModel.LType integerValue]]==LotteryNumTypeLottery){
            return _lotteryModel.LotteryArr.count;
        }
        return arrData.count;
        
    }
    
    
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    LotteryNumCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LotteryNumCell" forIndexPath:indexPath];
    if (collectionView==self.bottomCollectionView) {
        [cell setDownTitle:arrAlias[indexPath.row] andType:LotteryNumTypeLottery];
    }else{
        
        LotteryNumType type=[[BaseVM manage] getType:[_lotteryModel.LType integerValue]];
        if ([_lotteryModel.LType integerValue]==65) {
            [cell setTitle:_lotteryModel.PCArr[indexPath.row] andType:type];
        }else if (type==LotteryNumTypeLottery){
            [cell setTitle:_lotteryModel.LotteryArr[indexPath.row] andType:type];
        }else{
            [cell setTitle:arrData[indexPath.row] andType:type];
        }
        if ((type==LotteryNumTypeChromosphere||type==LotteryNumTypeBrings||type==LotteryNumTypeSevenLecai)&&(indexPath.row==_lotteryModel.numArr.count-1)) {
            [cell setBGColor:DEFAULTTEXTBLUECOLOR];
        }else if (type==LotteryNumTypeBrings&&(indexPath.row==_lotteryModel.numArr.count-2)){
            [cell setBGColor:DEFAULTTEXTBLUECOLOR];
        }
    }
    
 
    
    
    return cell;
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, -1, 0, 0);
}

- (UICollectionView *)collectionView{
    if (_collectionView==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake(real_size(27), real_size(27))];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.userInteractionEnabled=NO;
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator=NO;
        [_collectionView registerClass:[LotteryNumCell class] forCellWithReuseIdentifier:@"LotteryNumCell"];
    }
    return _collectionView;
}


- (UICollectionView *)bottomCollectionView{
    if (_bottomCollectionView==nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake(27, 27)];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _bottomCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _bottomCollectionView.delegate = self;
        _bottomCollectionView.dataSource = self;
        _bottomCollectionView.backgroundColor=[UIColor whiteColor];
        _bottomCollectionView.showsVerticalScrollIndicator=NO;
        [_bottomCollectionView registerClass:[LotteryNumCell class] forCellWithReuseIdentifier:@"LotteryNumCell"];
    }
    return _bottomCollectionView;
}


@end
